import turtle
import math
import time
import random  # 添加到文件开头
triangle_vertices = [(-300, -200), (0, 300), (300, -200)]

def calc_centroid(vertices):
    x_values = [vx for (vx, vy) in vertices]
    y_values = [vy for (vx, vy) in vertices]
    return (sum(x_values)/3, sum(y_values)/3)

# 初始化验证
print("计算质心:", calc_centroid(triangle_vertices))  # 输出 (0.0, -33.333333333333336)

# 初始化画布
screen = turtle.Screen()
screen.setup(width=800, height=800)
screen.title("三角形中心追击战")
screen.bgcolor("white")
screen.tracer(2)

# 创建人类（位于三角形质心）
human = turtle.Turtle()
human.shape("circle")
human.color("blue")
human.shapesize(1.5)
human.penup()
centroid = calc_centroid(triangle_vertices)
print(f"质心坐标: {centroid}")
human.goto(centroid)
human.pendown()
human.pensize(2)

# 创建鳄鱼（位于顶点）
crocodiles = []
speeds = [20, 20, 15]
colors = ["red", "green", "purple"]

for i, (vertex, speed, color) in enumerate(zip(triangle_vertices, speeds, colors)):
    croc = turtle.Turtle()
    croc.shape("square")
    croc.color(color)
    croc.shapesize(1.2)
    croc.penup()
    croc.goto(vertex)
    croc.pendown()
    croc.pensize(2)
    crocodiles.append((croc, speed))

# 修正后的边界绘制代码
border = turtle.Turtle()
border.hideturtle()
border.pencolor("gold")
border.pensize(2)
border.penup()

# 移动到第一个顶点（A点）
first_vertex = triangle_vertices[0]  # 获取第一个顶点坐标 (-300, -200)
border.goto(first_vertex)  # 移动到A点
border.write("顶点A", align="left")
border.pendown()

# 绘制到其他顶点
for vertex in triangle_vertices[1:]:
    border.goto(vertex)
    if vertex == (0, 300):
        border.write("顶点B", align="center")
    elif vertex == (300, -200):
        border.write("顶点C", align="right")

# 闭合三角形（回到A点）
border.goto(first_vertex)  # 回到第一个顶点坐标闭合三角形
border.penup()


# 移动逻辑（严格限制在三角形内）
def is_inside_triangle(point):
    # 使用重心坐标法判断点是否在三角形内
    x, y = point
    (x1, y1), (x2, y2), (x3, y3) = triangle_vertices

    denominator = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)
    a = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / denominator
    b = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / denominator
    c = 1 - a - b

    return (a >= -0.05) and (b >= -0.05) and (c >= -0.05)  # 允许5%的溢出容差


def move_human():
    dx_total, dy_total = 0, 0

    # 添加随机扰动打破平衡
    if step == 0:  # 只在第一步添加初始扰动
        dx_total += random.uniform(-5, 5)
        dy_total += random.uniform(-5, 5)

    for croc, _ in crocodiles:
        dx = human.xcor() - croc.xcor()
        dy = human.ycor() - croc.ycor()
        distance = math.hypot(dx, dy)
        if distance < 150:
            weight = 2.0
        else:
            weight = 1.0
        dx_total += (dx / distance) * weight
        dy_total += (dy / distance) * weight

    step_size = 15  # 增大步长让移动更明显
    candidate_x = human.xcor() + dx_total * step_size
    candidate_y = human.ycor() + dy_total * step_size

    if is_inside_triangle((candidate_x, candidate_y)):
        human.goto(candidate_x, candidate_y)
    else:
        tangent_dir = math.atan2(dy_total, dx_total) + math.pi / 2
        human.setheading(math.degrees(tangent_dir))
        human.forward(step_size * 0.8)  # 边界移动更快


def move_crocodiles():
    for croc, speed in crocodiles:
        dx = human.xcor() - croc.xcor()
        dy = human.ycor() - croc.ycor()
        distance = math.hypot(dx, dy)
        if distance == 0:
            continue

        # 动态调整鳄鱼速度（距离越近速度越快）
        dynamic_speed = speed * (1 + 0.5 / (distance / 100 + 0.1))
        croc.goto(
            croc.xcor() + (dx / distance) * dynamic_speed,
            croc.ycor() + (dy / distance) * dynamic_speed
        )


# 主程序
step = 0
while True:
    print(f"Step {step}: 人坐标 ({human.xcor():.1f}, {human.ycor():.1f})")
    move_human()
    screen.update()
    time.sleep(0.3)

    move_crocodiles()
    screen.update()
    time.sleep(0.3)

    if any(croc.distance(human) < 30 for croc, _ in crocodiles):
        human.color("red")
        human.write("被捕获!", font=("楷体", 24, "bold"))
        break
    step += 1

turtle.done()
